package com.x.mvp.base;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.x.mvp.R;
import com.x.mvp.injection.components.DaggerActivityComponent;
import com.squareup.leakcanary.RefWatcher;
import com.x.mvp.MVPApplication;
import com.x.mvp.injection.components.ActivityComponent;
import com.x.mvp.utils.ActivityAssistant;
import com.x.mvp.utils.StatusBarCompat;
import com.x.mvp.utils.StatusBarUtils;
import com.x.mvp.widget.AlartDialog;
import com.x.mvp.widget.AppProgress;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity {

    public static final String FIX_FRAGMENT_OVERLAPPING = "fix.fragment.overlapping";
    static final String FRAGMENTS_TAG = "android:support:fragments";


    protected int statusBarColor = 0;
    protected View statusBarView = null;

    private boolean fixFragmentOverlapping;

    private ActivityComponent activityComponent;
    private Unbinder unbinder;

    private ViewStub tipsViewStub;
    private View tipsView;

    private AppProgress appProgress;
    private AlartDialog alartDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        if (statusBarColor == 0) {
            statusBarView = StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.colorPrimaryDark));
        } else if (statusBarColor != -1) {
            statusBarView = StatusBarCompat.compat(this, statusBarColor);
        }
//        transparent19and20();
        unbinder = ButterKnife.bind(this);
//        translucentStatus();
        if (activityComponent == null) {
            activityComponent = MVPApplication.getInstance().getActivityComponent(this);
        }
    }

    protected void transparent19and20() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(FIX_FRAGMENT_OVERLAPPING, fixFragmentOverlapping);
        if (fixFragmentOverlapping) {
            // drop fragments state
            outState.putSerializable(FRAGMENTS_TAG, null);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        fixFragmentOverlapping = savedInstanceState.getBoolean(FIX_FRAGMENT_OVERLAPPING, false);
    }

    protected void fixFragmentOverlapping() {
        fixFragmentOverlapping = true;
    }

    protected ActivityComponent getActivityComponent() {
        return activityComponent;
    }

    protected abstract int getLayoutId();

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
        fixInputMethodManagerLeak(this);
        RefWatcher refWatcher = MVPApplication.getRefWatcher(this);
        refWatcher.watch(this);
    }

    private void translucentStatus() {
        StatusBarUtils.setColor(this, getResources().getColor(R.color.colorPrimaryDark));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) {
            ActivityAssistant.assistActivity(this);
        }
    }

    private void fixInputMethodManagerLeak(Context destContext) {
        if (destContext != null) {
            InputMethodManager imm = (InputMethodManager) destContext.getSystemService(
                    INPUT_METHOD_SERVICE);
            if (imm != null) {
                String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
                Field f = null;
                Object objGet = null;
                for (int i = 0; i < arr.length; i++) {
                    String param = arr[i];
                    try {
                        f = imm.getClass()
                                .getDeclaredField(param);
                        if (!f.isAccessible()) {
                            f.setAccessible(true);
                        }
                        objGet = f.get(imm);
                        if (objGet != null && objGet instanceof View) {
                            View vGet = (View) objGet;
                            if (vGet.getContext() == destContext) {
                                f.set(imm, null);
                            } else {
                                break;
                            }
                        }
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            }
        }
    }

    public void initTipsView() {
        if (getTipsStubViewId() > 0) {
            tipsViewStub = (ViewStub) findViewById(getTipsStubViewId());
            if (getTipsRootViewLayoutId() > 0) {
                tipsViewStub.setLayoutResource(getTipsRootViewLayoutId());
                tipsView = tipsViewStub.inflate();
            }
        }
    }

    public View getTipsView() {
        if (tipsViewStub == null) {
            initTipsView();
        }
        return tipsView;
    }

    public int getTipsStubViewId() {
        return R.id.tips;
    }

    public int getTipsRootViewLayoutId() {
        return R.layout.mvp_layout_coordinator;
    }

    public void showTips(int resId) {
        toast(resId, Toast.LENGTH_SHORT);
    }

    public void showTips(String msg) {
        toast(msg);
    }

    public void toast(int resId, int length) {
        Toast.makeText(this, getString(resId), length).show();
    }

    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected AppProgress newAppProgress() {
        return AppProgress.getAppProgress(this, true, null);
    }

    public void showAppProgress() {
        if (appProgress == null) {
            appProgress = newAppProgress();
        }
        appProgress.show();
    }

    public void hideAppProgress() {
        if (appProgress != null) {
            appProgress.dismiss();
        }
    }

    protected AlartDialog newAlartDialog() {
        return new AlartDialog(this);
    }

    public void showAlartDialog(int type, String message, int time) {
        if (alartDialog == null) {
            alartDialog = newAlartDialog();
        }
        alartDialog.showMessage(type, message, time);
    }

    public void hideAlartDialog() {
        if (alartDialog != null) {
            alartDialog.dismiss();
            alartDialog.setiDissmiss(iDissmiss);
        }
    }

    public AlartDialog.IDissmiss iDissmiss = new AlartDialog.IDissmiss() {
        @Override
        public void onDismiss(int type) {
            dismissAlartDialog(type);
        }
    };

    public void dismissAlartDialog(int type){

    }

}
